﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using JUtil;

namespace SqlConnectionSettings
{
    public partial class SqlConnectionSettings : Form
    {
        public SqlConnectionSettings(DatabaseMode mode, string ConnectionString)
        {
            InitializeComponent();

            Initialize(mode, ConnectionString);
        }

        public SqlConnectionSettings()
        {
            InitializeComponent();

            Initialize();
        }

        private void Initialize()
        {
            cbDatabaseMode.Items.Clear();
            foreach (DatabaseMode mode in Enum.GetValues(typeof(DatabaseMode)))
            {
                cbDatabaseMode.Items.Add(mode);
            }
            if (cbDatabaseMode.Items.Count != 0)
                cbDatabaseMode.SelectedIndex = 0;

            tbConnectionString.Clear();
        }

        private void Initialize(DatabaseMode mode, string ConnectionString)
        {
            Initialize();

            cbDatabaseMode.SelectedItem = mode;

            tbConnectionString.Text = ConnectionString;
        }

        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            DatabaseMode mode = (DatabaseMode)Enum.Parse(typeof(DatabaseMode), cbDatabaseMode.SelectedItem.ToString());
            
            string ConnectionString = tbConnectionString.Text;

            //mode = DatabaseMode.OleDb;
            //ConnectionString = @"Provider=SQLOLEDB.1;Password=sapass;Persist Security Info=True;User ID=sa;Data Source=JELLY\SQLEXPRESS";

            IDatabase db = new Database(mode, ConnectionString);

            try
            {
                if (db.TestConnection() == true)
                {
                    ExtMessageBox.Info("連線成功", "連線測試");
                }
                else
                {
                    ExtMessageBox.Error("連線失敗", "連線測試");
                }
            }
            catch (Exception ex)
            {
            	Log.ReportError(ex);
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        public DatabaseMode GetDatabaseMode() { return (DatabaseMode)cbDatabaseMode.SelectedItem; }
        public string GetConnectionString() { return tbConnectionString.Text; }
    }
}
